package com.egame.manage.biz.utils;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import test.AXMLPrinter;

import cn.egame.common.util.Utils;
public class AndroidInfoUtils {
	public static void main(String[] args) {
		System.out.println(new AndroidInfoUtils().parseAndroidInfo("E:\\com.yijia.1364467555578.apk")[0]);
	}

	/** 安卓apk包名称 */
	private String packageName;

	/** 安卓apk包版本名称 */
	private String versionName;

	/** 安卓apk包版本代码 */
	private String versionCode;

	/**
	 * 获取安卓apk包的基本信息
	 * 
	 * @param String apkFilePath apk包路径
	 * 
	 * @return String[] 数组中的值分别为{packageName,versionName,versionCode}
	 * 
	 */
	public String[] parseAndroidInfo(String apkFilePath) {
		//apkFilePath = "E:\\com.yijia.1364467555578.apk";
		InputStream inputStream = null;
		FileOutputStream outStream = null;
		try {
			// 1.读取安卓包中的AndroidManifest.xml文件并临时写到服务器上
			ZipFile zipFile = new ZipFile(apkFilePath);
			ZipEntry zipEntry = zipFile.getEntry("AndroidManifest.xml");
			inputStream = zipFile.getInputStream(zipEntry);
			byte[] buffer = new byte[1024];
			int length;
			outStream = new FileOutputStream(new File("AndroidManifest.xml"));
			while (-1 != (length = inputStream.read(buffer))) {
				outStream.write(buffer, 0, length);
			}
			outStream.close();
			inputStream.close();
			//String thirdJarPath = "AXMLPrinter2.jar";
			String thirdJarPath = AXMLPrinter.class.getProtectionDomain().getCodeSource().getLocation().getFile();
//			if(!Utils.stringIsNullOrEmpty(thirdJarPath)){
//				thirdJarPath = thirdJarPath.substring(1);
//			}
			// 2.组装反编译执行的命令行
			String command = "java -jar " + thirdJarPath + " AndroidManifest.xml ";
			System.out.println(command);
			// 3.执行命令
			Process process = Runtime.getRuntime().exec(command);
			// 4.解析关键信息
			BufferedReader buffReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String content = "", message = "";
			while ((message = buffReader.readLine()) != null) {
				content += message + "\n";
				System.out.println(message);
			}
			buffReader.close();
			if(!Utils.stringIsNullOrEmpty(content)){
				ByteArrayInputStream byteInputStream = new ByteArrayInputStream(content.getBytes("utf-8"));
				SAXParserFactory saxFactory = SAXParserFactory.newInstance();
				saxFactory.setValidating(false);
				saxFactory.setNamespaceAware(false);
				SAXParser saxParser = saxFactory.newSAXParser();
				saxParser.parse(byteInputStream, new DefaultHandler() {
					@Override
					public void characters(char[] ch, int start, int length) throws SAXException {
						super.characters(ch, start, length);
					}

					@Override
					public void endDocument() throws SAXException {
						super.endDocument();
					}

					@Override
					public void endElement(String uri, String localName, String qName) throws SAXException {
						super.endElement(uri, localName, qName);
					}

					@Override
					public void startDocument() throws SAXException {
						super.startDocument();
					}

					@Override
					public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
						if (qName.equals("manifest")) {
							for (int i = 0; i < attributes.getLength(); i++) {
								String strQname = attributes.getQName(i);
								if (strQname.equals("package")) {
									packageName = attributes.getValue(strQname);
								}
								if (strQname.equals("android:versionName")) {
									versionName = attributes.getValue(strQname);
								}
								if (strQname.equals("android:versionCode")) {
									versionCode = attributes.getValue(strQname);
								}
							}
						}
						super.startElement(uri, localName, qName, attributes);
					}
				});
			}else{
				packageName = "";
				versionName = "";
				versionCode = "";
			}
			
		} catch (Exception e) {
			e.printStackTrace();			
		}
		return new String[] { packageName, versionName, versionCode };
	}

	/**
	 * 获取指定目录下的所有apk文件全路径
	 * 
	 * @param path 安卓实体文件所在路径
	 * 
	 * @return List<String>
	 * 
	 */
	public List<String> getAllApkFiles(String path) {
		List<String> list = null;
		File file = new File(path);
		String[] files = file.list(new FilenameFilter() {
			@Override
			public boolean accept(File dir, String name) {
				if (name.matches(".*\\.(?i)(apk)")) {
					return true;
				} else {
					return false;
				}
			}
		});
		if (files != null && files.length > 0) {
			list = new ArrayList<String>();
			for (int index = 0; index < files.length; index++) {
				if (files[index].matches(".*\\.(?i)(apk)")) {
					if (files[index].length() > 0) {
						list.add(path + File.separator + files[index]);
					}
				}
			}
		}
		return list;
	}

	public String getPackageName() {
		return packageName;
	}

	public String getVersionName() {
		return versionName;
	}

	public String getVersionCode() {
		return versionCode;
	}
}
